/* Copyright (c) 2010 OFXKit
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#import "OFXSecurityRequest.h"


@implementation OFXSecurityRequest

@synthesize security;

- (NSString*)formRequestForOFXVersion:(NSUInteger)ofxVersion
{
  if (ofxVersion >= 100 && ofxVersion <= 106) {
    return [self formOFX1Request];
  } else if (ofxVersion >= 200 && ofxVersion <= 211) {
    return [self formOFX2Request];
  }
  
  // unsupported version of ofx requested
  return nil;
}

- (NSString*)formOFX1Request
{
  return [self formOFX2Request];
}

- (NSString*)formOFX2Request
{
  NSString* result = nil;
  if ([security uniqueId] != nil &&
      [security uniqueIdType] != nil) {
    result = [NSString stringWithFormat:@"<SECID><UNIQUEID>%@</UNIQUEID>"
              "<UNIQUEIDTYPE>%@</UNIQUEIDTYPE></SECID>",
              [security uniqueId], [security uniqueIdType]];
  } else if ([security tickerSymbol] != nil) {
    result = [NSString stringWithFormat:@"<TICKER>%@</TICKER>", 
              [security tickerSymbol]];
  } else if ([security financialInstitutionSecurityId] != nil) {
    result = [NSString stringWithFormat:@"<FIID>%@</FIID>", 
              [security financialInstitutionSecurityId]];
  } else {
    // raise an exception because an invalid security was passed in
    NSException *exception = [NSException exceptionWithName:@"InvalidOption"
                                                     reason:@"Security must "
                              "contain uniqueId and uniqueIdType, or "
                              "tickerSymbol, or financialInstitutionSecurityId"
                                                   userInfo:nil];
    @throw exception;
  }
  
  return result;
}

@end
